package cpu_cards_service

import (
	"heyzhima-yt-cpu/models"
	"heyzhima-yt-cpu/pkg/gredis"
	"heyzhima-yt-cpu/pkg/logging"
	"heyzhima-yt-cpu/service/cache_service"
	"encoding/json"
	"fmt"
)
type CpuCards struct {
	ID            int
	CardCode         string
	CardSecret         string
	ZoneId          int
	CreatedAt     int64
	UpdatedAt     int64
	DeletedAt     int64
}

type  Res struct{
	UserName string
	UserMobile string
	BuildingNamePath string
	CardId         int
	Uid            string
	CardCode       string
	CardNum        string
	CardExpired    int64
	CardType       string
	CardFunc       string
	CardDisabled   string
	CardDesc       string
	CardScan       string
	ZoneId         int
	BuildingId     string
	UserId         string
	RoomId         string
	AgentAccountId string
	AccountId      string
	LastUse        string
	CreatedAt      int64
	UpdatedAt      int64
	DeletedAt      int
}


func (a *CpuCards) GetCpuCardInfo(code string,zone int) ([]*models.Res, error){
	var cacheCpuCards []*models.Res
	cache := cache_service.CpuCards{ID: a.ID}
	key := cache.GetCpuCardKey(code)
	if gredis.Exists(key) {
		data, err := gredis.Get(key)
		if err != nil {
			logging.Info(err)
		} else {
			json.Unmarshal(data, &cacheCpuCards)
			return cacheCpuCards, nil
		}
	}
	cardsInfo, err := models.GetCpuCardsInfo(code,zone)
	fmt.Println(cardsInfo)
	if err != nil {
		return nil, err
	}

	gredis.Set(key, cardsInfo, 3600)
	return cardsInfo, nil
}




func (a *CpuCards) CpuCardsByCode() (string, error) {
	return models.CpuCardsByCode(a.CardCode)
}

func (a *CpuCards) ExistByID() (bool, error) {
	fmt.Println(a.CardCode)
	return models.ExistCpuCardsByID(a.CardCode)
}

func (a *CpuCards) Update(secret string) (bool, error) {
	return models.Update(a.CardCode,secret)
}

func (a *CpuCards) Add() error {
	cpu_cards := map[string]interface{}{
		"id":          a.ID,
		"card_code":           a.CardCode,
		"card_secret":            a.CardSecret,
		"zone_id":         a.ZoneId,
		"created_at":      a.CreatedAt,
		"updated_at":      a.UpdatedAt,
	}

	if err := models.AddCpuCards(cpu_cards); err != nil {
		return err
	}

	return nil
}